package me.joshua.demo4j.swift.first;

import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.List;

import me.joshua.demo4j.swift.first.model.LogEntry;
import me.joshua.demo4j.swift.first.service.Scribe;
import me.joshua.demo4j.swift.first.service.SwiftScribeImpl;

import org.apache.thrift.TProcessor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.facebook.nifty.client.FramedClientConnector;
import com.facebook.nifty.client.NiftyClientChannel;
import com.facebook.nifty.client.NiftyClientConnector;
import com.facebook.swift.codec.ThriftCodecManager;
import com.facebook.swift.service.ThriftClientManager;
import com.facebook.swift.service.ThriftServer;
import com.facebook.swift.service.ThriftServerConfig;
import com.facebook.swift.service.ThriftServiceProcessor;

/**
 * @author <a href="mailto:daonan.zhan@gmail.com">Joshua Zhan</a>
 */
public class Demo {

	private static final int SCRIBE_SERVICE_PORT = 8899;
	private ThriftServer server;
	private ThriftClientManager clientManager;
	private SwiftScribeImpl internalScribe;
	private Scribe scribe;

	@Before
	public void init() {
		initServer();
		initClient();
	}

	@After
	public void destroy() {
		clientManager.close();
		server.close();
	}

	private void initServer() {
		internalScribe = new SwiftScribeImpl();
		TProcessor processor = new ThriftServiceProcessor(
				new ThriftCodecManager(), internalScribe);
		server = new ThriftServer(processor,
				new ThriftServerConfig().setPort(SCRIBE_SERVICE_PORT));
		server.start();
	}

	private void initClient() {
		clientManager = new ThriftClientManager();
		NiftyClientConnector<? extends NiftyClientChannel> connector = new FramedClientConnector(
				new InetSocketAddress("localhost", SCRIBE_SERVICE_PORT));
		try {
			scribe = clientManager.createClient(connector, Scribe.class).get();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Test
	public void test() {
		List<LogEntry> logList = new LinkedList<LogEntry>();
		logList.add(new LogEntry("demo", "Hello world"));
		scribe.log(logList);

		logList = internalScribe.getMessages();
		for (LogEntry log : logList) {
			System.out.println(log);
		}
	}
}